from flask import Flask
from flask_cors import CORS
from config import config_by_name
from models import db


def create_app(config_name='default'):
    """Flask 应用工厂函数"""
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(config_by_name[config_name])
    
    # 初始化扩展
    # 细化跨域配置，确保预检请求通过
    CORS(app, resources={
        r"/api/*": {
            "origins": [
                "http://localhost:8080",
                "http://127.0.0.1:8080"
            ],
            "allow_headers": ["Content-Type", "Authorization"],
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
            "supports_credentials": True,
            "max_age": 86400
        }
    })  # 允许前端跨域
    
    # 初始化数据库
    try:
        db.init_app(app)
        print("数据库初始化成功")
    except Exception as e:
        print(f"数据库初始化失败: {e}")
    
    # 注册蓝图
    try:
        from router import health_bp, test_qwen_bp, test_table_bp, preprocess_bp, align_bp, retrieve_bp, llm_bp, history_bp
        from router.auth import auth_bp
        from router.rbac import rbac_bp
        
        app.register_blueprint(health_bp)
        app.register_blueprint(test_qwen_bp)
        app.register_blueprint(test_table_bp)
        app.register_blueprint(preprocess_bp, url_prefix='/api')
        app.register_blueprint(align_bp, url_prefix='/api')
        app.register_blueprint(retrieve_bp, url_prefix='/api')
        app.register_blueprint(llm_bp, url_prefix='/api')
        app.register_blueprint(history_bp, url_prefix='/api')
        app.register_blueprint(auth_bp, url_prefix='/api/auth')
        app.register_blueprint(rbac_bp, url_prefix='/api/admin')
        
        print("所有蓝图注册成功")
        print("认证路由已注册: /api/auth/register (POST)")
        print("LLM路由已注册: /api/llm/process (POST)")

    except Exception as e:
        print(f"蓝图注册失败: {e}")
        import traceback
        traceback.print_exc()

    # 创建数据库表
    try:
        with app.app_context():
            db.create_all()
            print("数据库表创建成功")
    except Exception as e:
        print(f"数据库表创建失败: {e}")
        print("请检查数据库连接配置")
    
    # 添加错误处理
    @app.errorhandler(405)
    def method_not_allowed(error):
        return {
            'error': 'Method Not Allowed',
            'message': '请求方法不被允许。注册接口需要使用POST方法。',
            'allowed_methods': ['POST']
        }, 405
    
    @app.errorhandler(404)
    def not_found(error):
        return {
            'error': 'Not Found',
            'message': '请求的资源不存在'
        }, 404
    
    return app


if __name__ == '__main__':
    app = create_app('development')
    app.run(debug=True, host='127.0.0.1', port=5000)